package com.example.demo01.controller;

import com.example.demo01.pojo.User;
import com.example.demo01.service.AdminService;
import com.example.demo01.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class RootController {
    @Autowired
    UserService userService;
    @Autowired
    AdminService adminService;

    @RequestMapping("/root/getAllAdmins")
    public String getAllAdmins(Model model){
        List<User> admins=adminService.getAllAdmins();
        model.addAttribute("admins", admins);

        return "getAllAdmins";
    }


    @RequestMapping("/root/freezeAdminByName/{username}")
    public String freezeAdminByName(@PathVariable("username") String username){

        userService.updateActiveWithFalse(username);

        return "redirect:/root/getAllAdmins";
    }



    @RequestMapping("/root/unFreezeAdminByName/{username}")
    public String unFreezeAdminByName(@PathVariable("username") String username){

        userService.updateActiveWithTrue(username);

        return "redirect:/root/getAllAdmins";
    }



    @RequestMapping("/root/jumpToAddAdminInput")
    public String jumpToAddAdminInput(){
        return "addAdminInput";
    }


    @RequestMapping("/root/addAdmin")
    public String addAdmin(String username, String password, Model model){

        User user=userService.getUserByName(username);


        if(user==null){
            User newUser=new User(null,username,"{noop}"+password,"是","ROLE_ADMIN");

            userService.addUser(newUser);

            return "redirect:/root/getAllAdmins";
        }else{//用户名已存在

            model.addAttribute("usernameExistErrorMessage","用户名已存在！");
            return "addAdminInput";
        }



    }



}
